package com.carful.xigua.modules.common.advice;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Arrays;

/**
 * @author ad
 * Date 2024/6/6 10:57
 */

@Aspect
@Slf4j
@Component("GlobalControllerAdvice")
@Order(1)
public class GlobalControllerAdvice {

    @Pointcut("execution(public * cc.cctvs.canteen.modules.*.controller.*.*(..))")
    public void log() {

    }

    @Around(value = "log()")
    public Object logInter(ProceedingJoinPoint joinPoint) throws Throwable {
        String className = "";
        String methodName = "";
        try {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = servletRequestAttributes.getRequest();
            Object[] args = joinPoint.getArgs();

            Object target = joinPoint.getTarget();
            className = target.getClass().getName();  //当前执行的方法所属的类、包

            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            methodName = signature.getName();  //当前执行的方法名称

            log.info(className + " " + methodName + " \nargs: " + Arrays.toString(args));
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        Object proceed = joinPoint.proceed(joinPoint.getArgs());

        try {
            String s = proceed.toString();
            log.info(className + " " + methodName + " \nres:" + s.substring(0, Math.min(200, s.length())));
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return proceed;
    }
}
